package cn.iocoder.yudao.module.xiaoBizHandler.controller.admin.tbFile;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.module.xiaoBizHandler.controller.admin.tbFile.vo.*;
import cn.iocoder.yudao.module.xiaoBizHandler.convert.tbFile.XTbFileConvert;
import cn.iocoder.yudao.module.xiaoBizHandler.dal.dataobject.attach.AttachDO;
import cn.iocoder.yudao.module.xiaoBizHandler.dal.dataobject.tbFile.XTbFileDO;
import cn.iocoder.yudao.module.xiaoBizHandler.dal.dataobject.tbFolder.XTbFolderDO;
import cn.iocoder.yudao.module.xiaoBizHandler.service.attach.AttachService;
import cn.iocoder.yudao.module.xiaoBizHandler.service.tbFile.XTbFileService;
import cn.iocoder.yudao.module.xiaoBizHandler.service.tbFolder.XTbFolderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;

@Api(tags = "管理后台 - 文件")
@RestController
@RequestMapping("/xiaoBizHandler/XT-b-file")
@Validated
public class XTbFileController {

    @Resource
    private XTbFileService xTbFileService;

    @Resource
    private AttachService attachService;

    @Resource
    private XTbFolderService folderService;


    @PostMapping("/create")
    @ApiOperation("创建文件")
    @PreAuthorize("@ss.hasPermission('xbh:XT-b-file:create')")
    public CommonResult<String> createXTbFile(@Valid @RequestBody XTbFileCreateReqVO createReqVO) {
        attachService.refreshAttach(createReqVO.getFilePath(), createReqVO.getFileName(), createReqVO.getId());
        return success(xTbFileService.createXTbFile(createReqVO));
    }

    @PutMapping("/update")
    @ApiOperation("更新文件")
    @PreAuthorize("@ss.hasPermission('xbh:XT-b-file:update')")
    public CommonResult<Boolean> updateXTbFile(@Valid @RequestBody XTbFileUpdateReqVO updateReqVO) throws IOException {
        attachService.refreshAttach(updateReqVO.getFilePath(), updateReqVO.getFileName(), updateReqVO.getId());
        xTbFileService.updateXTbFile(updateReqVO);
        refreshFile(updateReqVO.getId());
        return success(true);
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除文件")
    @ApiImplicitParam(name = "id", value = "编号", required = true, dataTypeClass = String.class)
    @PreAuthorize("@ss.hasPermission('xbh:XT-b-file:delete')")
    public CommonResult<Boolean> deleteXTbFile(@RequestParam("id") String id) {
        attachService.deleteAttach(xTbFileService.getXTbFile(id).getFilePath());
        xTbFileService.deleteXTbFile(id);
        return success(true);
    }

    @GetMapping("/get")
    @ApiOperation("获得文件")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = String.class)
    @PreAuthorize("@ss.hasPermission('xbh:XT-b-file:query')")
    public CommonResult<XTbFileRespVO> getXTbFile(@RequestParam("id") String id) {
        XTbFileDO xTbFile = xTbFileService.getXTbFile(id);
        XTbFileRespVO rs = XTbFileConvert.INSTANCE.convert(xTbFile);
        // 文件大小格式转换
        AttachDO attach = attachService.getAttach(xTbFile.getFilePath());
        rs.setFileSizeFormatter(FileUtil.readableFileSize(attach.getAttachSize().longValue()));
        // 附件id转换为附件的绝对路径
        rs.setFileAbsolutePathFormatter(attachService.getAttachPath(xTbFile.getFilePath()));
        return success(rs);
    }

    @GetMapping("/list")
    @ApiOperation("获得文件列表")
    @ApiImplicitParam(name = "ids", value = "编号列表", required = true, example = "1024,2048", dataTypeClass = List.class)
    @PreAuthorize("@ss.hasPermission('xbh:XT-b-file:query')")
    public CommonResult<List<XTbFileRespVO>> getXTbFileList(@RequestParam("ids") Collection<String> ids) {
        List<XTbFileDO> list = xTbFileService.getXTbFileList(ids);
        return success(XTbFileConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/page")
    @ApiOperation("获得文件分页")
    @PreAuthorize("@ss.hasPermission('xbh:XT-b-file:query')")
    public CommonResult<PageResult<XTbFilePageItemRespVO>> getXTbFilePage(@Valid XTbFilePageReqVO pageVO) {
        PageResult<XTbFileDO> pageResult = xTbFileService.getXTbFilePage(pageVO);

        List<XTbFileDO> list = pageResult.getList();
        // 获取拼接所需要的数据
        List<String> folderIds = CollectionUtils.convertList(pageResult.getList(), XTbFileDO::getFolderId);
        Map<String, XTbFolderDO> folderMap = folderService.getFolderMap(folderIds);
        // 拼接结果并返回
        List<XTbFilePageItemRespVO> fileList = new ArrayList<>(pageResult.getList().size());
        pageResult.getList().forEach(file -> {
            XTbFilePageItemRespVO respVO = XTbFileConvert.INSTANCE.convert02(file);
//            BeanUtil.copyProperties(file, respVO,true);
            XTbFolderDO xTbFolderDO = folderMap.get(file.getFolderId());
            // 文件夹
            respVO.setFolder(XTbFileConvert.INSTANCE.convert02(xTbFolderDO));
            // 文件大小格式转换
            AttachDO attach = attachService.getAttach(file.getFilePath());
            respVO.setFileSizeFormatter(FileUtil.readableFileSize(attach.getAttachSize().longValue()));
            // 附件id转换为附件的绝对路径
            respVO.setFileAbsolutePathFormatter(attachService.getAttachPath(file.getFilePath()));
            fileList.add(respVO);
        });
        return success(new PageResult<>(fileList, pageResult.getTotal()));
    }

    @GetMapping("/export-excel")
    @ApiOperation("导出文件 Excel")
    @PreAuthorize("@ss.hasPermission('xbh:XT-b-file:export')")
    @OperateLog(type = EXPORT)
    public void exportXTbFileExcel(@Valid XTbFileExportReqVO exportReqVO,
              HttpServletResponse response) throws IOException {
        List<XTbFileDO> list = xTbFileService.getXTbFileList(exportReqVO);
        // 导出 Excel
        List<XTbFileExcelVO> datas = XTbFileConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "文件.xls", "数据", XTbFileExcelVO.class, datas);
    }


    @PutMapping("/openFile")
    @ApiOperation("打开文件")
    @PreAuthorize("@ss.hasPermission('xbh:XT-b-file:openFile')")
    public void openXTbFile(@RequestParam("absolutePath") String absolutePath) throws IOException {
        xTbFileService.openFile(absolutePath);
    }

    @PutMapping("/refreshFile")
    @ApiOperation("刷新文件信息")
    @PreAuthorize("@ss.hasPermission('xbh:XT-b-file:refreshFile')")
    public void refreshFile(@RequestParam("id") String id) throws IOException {
        xTbFileService.refreshFile(id);
    }

    @PostMapping("/createFile")
    @ApiOperation("创建文件")
    @PreAuthorize("@ss.hasPermission('xbh:XT-b-file:createFile')")
    public void createFile(@Valid @RequestBody XTbFileCreateReqVO createReqVO) throws IOException {
        xTbFileService.createFile(createReqVO);
    }

    @PostMapping("/createAndOpenFile")
    @ApiOperation("创建并打开文件")
    @PreAuthorize("@ss.hasPermission('xbh:XT-b-file:createAndOpenFile')")
    public void createAndOpenFile(@Valid @RequestBody XTbFileCreateReqVO createReqVO) throws IOException {
        xTbFileService.createAndOpenFile(createReqVO);
    }

}
